import axios from 'axios';
import secret from './secret';
import Helper from './helper';
import Base from '@/api/base';

// 全局的 axios值
console.log("环境地址改变--------------",process.env,+'1111111111111'+__dirname);
axios.defaults.baseURL = process.env.VUE_APP_API_URL;
axios.defaults.timeout = 50000;
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.withCredentials = true

export const APPNAME = 'web_back'
export const APPVERSION = '1.0'

// 添加请求拦截器
// axios.interceptors.request.use(function (config) {
//   if (Helper.get('token') && Helper.get('token') !== 'null') {
//     // config.headers['X-Token'] = Helper.get('token');
//     config.headers['X-Token'] = '95aa7dcfa34b4011a7dcce449bf54f28#U88025';
//   }
//   config.headers['X-Token'] = '95aa7dcfa34b4011a7dcce449bf54f28#U88025';
//   config.data['appName'] = APPNAME;
//   config.data['appVersion'] = APPVERSION;
//   // console.log('打印明文参数：' + JSON.stringify(config.data));
//   let params = {
//     param: secret.Encrypt(JSON.stringify(config.data))
//   };
//   config.data = params;
//   return config;
// }, function (error) {
//   return Promise.reject(error);
// });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {

  return response;
}, function (error) {
  return Promise.reject(error);
});

/**
  * post请求
  * @param {String} url [请求的url地址]
  * @param {Object} params [请求时携带的参数]
  */
const ERR_OK = 0;
export function apiPost(url, params = {}) {
  return new Promise((resolve, reject) => {
    const load = Helper.loading('正在加载中...');
    axios.post(url, params)
      .then(res => {
        let { status, data } = res.data;
        if (parseInt(status.code) === ERR_OK) {
          let decryptData = secret.Decrypt(data);
          let dataJson = null;
          if (decryptData !== '{}') {
            dataJson = JSON.parse(decryptData);
          }
          // console.log('打印明文', dataJson);

          resolve(dataJson);
        } else {
          Helper.error(status.msg);
          reject(status.msg);
          // token 失效
          if (parseInt(status.code) === 401) {
            var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
            if (keys) {
              for (var i = keys.length; i--;) {
                document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString();
              }
            }
            localStorage.clear();
            sessionStorage.clear();
            window.location.href = '/login';
          }
        }
      })
      .catch(err => {
        reject(err.data);
      })
      .finally(() => {
        setTimeout(load, 0);
      });
  });
}
export function apiPostNoLoad(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(res => {
        let { status, data } = res.data;
        if (parseInt(status.code) === ERR_OK) {
          let decryptData = secret.Decrypt(data);
          let dataJson = null;
          if (decryptData !== '{}') {
            dataJson = JSON.parse(decryptData);
          }
          resolve(dataJson);
        } else {
          // Helper.error(status.msg);
          reject(status.msg);
        }
      })
      .catch(err => {
        reject(err.data);
      })
      .finally(() => {
      });
  });
}
export function apiUpload(formData = {}) {
  return new Promise((resolve, reject) => {
    const load = Helper.loading('正在上传中...');
    axios({
      method: 'post',
      url: Base.uploadImage,
      headers: { 'Content-Type': 'multipart/form-data', 'X-Token': Helper.get('token') },
      data: formData
    }).then(res => {
      let { status, data } = res.data;
      if (parseInt(status.code) === ERR_OK) {
        let decryptData = secret.Decrypt(data);
        let dataJson = null;
        if (decryptData !== '{}') {
          dataJson = JSON.parse(decryptData);
        }
        resolve(dataJson);
      } else {
        Helper.error(status.msg);
        reject(status.msg);
      }
    })
      .catch(err => {
        reject(err.data);
      })
      .finally(() => {
        setTimeout(load, 0);
      });
  });
}

/**
 * 导出功能
 */
export function buildExport(name, url, params = {}) {
  console.log("传入的参数-------------",params)
  axios({
    method: 'post',
    url: url,
    data: params,
    responseType: 'blob'
  }).then(res => {
    const link = document.createElement('a')
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    link.setAttribute('download', `${name}.xls`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link);
  }).catch(err => {
    console.log('导出报错', err);
  });
}
export const __COMMONAPI__ = process.env.VUE_APP_API_URL
